package com.partsoft.dits.integrate;



import java.util.Map;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.ContextStoppedEvent;
import org.springframework.util.ClassUtils;
import org.springframework.util.ObjectUtils;

import com.partsoft.dits.ConfigurableBean;
import com.partsoft.dits.DescriptorDepends;
import com.partsoft.dits.EdgeDescriptor;
import com.partsoft.dits.log.Log;

public class ContextAutoAssemblyDescriptorDependsManager extends
		BaseDescriptorDependsManager implements DescriptorDepends<EdgeDescriptor>,
		ApplicationContextAware, ApplicationListener<ApplicationEvent>, ConfigurableBean {

	private ApplicationContext ownerContext;
	
	public ApplicationContext getOwnerContext() {
		return ownerContext;
	}

	public void setOwnerContext(ApplicationContext ownerContext) {
		this.ownerContext = ownerContext;
	}

	public void setApplicationContext(ApplicationContext context) throws BeansException {
		setOwnerContext(context);
	}
	
	public void finiContext() {
		synchronized (this) {
			clearDescriptorDepends();
		}
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public void initContext() {
		synchronized (this) {
			Map<String, DescriptorDepends> depMaps = getOwnerContext().getBeansOfType(DescriptorDepends.class);
			for (Map.Entry<String, DescriptorDepends> depEntiry : depMaps.entrySet()) {
				if (ObjectUtils.nullSafeEquals(this, depEntiry.getValue())) continue;
				StringBuffer buffer = new StringBuffer();
				buffer.append("自动注册依赖处理器(").append(ClassUtils.getUserClass(depEntiry.getValue()).getName()).append(")");
				Log.info(buffer.toString());
				addDescriptorDepends(depEntiry.getValue());
			}
		}
	}

	public void onApplicationEvent(ApplicationEvent event) {
		if (getOwnerContext() == null)
			return;
		if (!ObjectUtils.nullSafeEquals(getOwnerContext(), event.getSource()))
			return;
		if (event instanceof ContextRefreshedEvent) {
			initContext();
		} else if (event instanceof ContextStoppedEvent) {
			finiContext();
		}
	}

}
